package com.chapter05;

import com.bdqn.util.JDBCUtils;

import java.net.CookieHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test04_Batch {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        long start = System.currentTimeMillis();

        Connection connection = JDBCUtils.getConnection();

        connection.setAutoCommit(false);

        String sql = "INSERT INTO goods(`name`) VALUES(?)";
        PreparedStatement statement = connection.prepareStatement(sql);

        for (int i = 1; i <= 20000; i++) {
            statement.setString(1, "zhangsan" + i);

            // ①、攒SQL
            statement.addBatch();

            if (i % 5000 == 0){
                // ②、执行SQL
                statement.executeBatch();

                // ③、清空batch
                statement.clearBatch();
            }

//            statement.setString(1, "zhangsan" + i);
//            statement.executeUpdate();
        }

        // connection.commit();


        JDBCUtils.closeResource(connection, statement, null);

        long end = System.currentTimeMillis();
        System.out.println(end - start);
        // statement: 51662ms
        // preparedstatement: 56398ms
        // 批处理：369 386:377 445 380 376
    }
}
